package com.gpt.article.service.impl.taskHandle;

import chatgpt.ChatGPT;
import chatgpt.entity.chat.ChatCompletion;
import chatgpt.entity.chat.ChatCompletionResponse;
import com.ruoyi.common.config.RuoYiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GptRequstHelper {
    private static Logger logger = LoggerFactory.getLogger(GptRequstHelper.class);
    int rgpttimes = 0;
    int chatCompletiontimes = 0;

    public  ChatGPT getGpt(ChatGPT chatGPT){
        try {
            chatGPT = ChatGPT.builder()
                    .apiKey(RuoYiConfig.getApiKeys())
                    .timeout(9000)
//                .proxy(proxy)
                    .apiHost(RuoYiConfig.getGptApiHost()) //代理地址
                    .build()
                    .init();
        }catch (Exception e){
            logger.error("丢包或者请求异常重试");

            while (rgpttimes < 3) {
                try {
                    chatGPT = ChatGPT.builder()
                            .apiKey(RuoYiConfig.getApiKeys())
                            .timeout(9000)
//                .proxy(proxy)
                            .apiHost(RuoYiConfig.getGptApiHost()) //代理地址
                            .build()
                            .init();


                    return chatGPT;
                } catch (Exception e2) {
                    System.out.println("重试次数"+rgpttimes+e2.getMessage());
                    rgpttimes++;
                    if(rgpttimes >= 3) {
                        throw new RuntimeException(e);
                    }
                }
            }

        }
        return chatGPT;
    }


    /**
     * 重试 chatCompletion
     * @param chatGPT
     * @param chatCompletion
     * @return
     */
    public ChatCompletionResponse getGptResponse(ChatGPT chatGPT,ChatCompletion chatCompletion){
        ChatCompletionResponse response = null;
        try {
            response = chatGPT.chatCompletion(chatCompletion);
        }catch (Exception e){
            logger.error("丢包或者请求异常重试");

            while (rgpttimes < 3) {
                try {
                    response = chatGPT.chatCompletion(chatCompletion);
                    return response;
                } catch (Exception e2) {
                    System.out.println("重试次数"+rgpttimes+e2.getMessage());
                    rgpttimes++;
                    if(rgpttimes >= 3) {
                        throw new RuntimeException(e);
                    }
                }
            }

        }
        return response;
    }


}
